import os
import sys
import math
import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()

from apps.supply_order.models import Goods
from apps.supply_order.models import Inventory
from apps.supply_order.models import GoodsImage
from apps.supply_order.models import GoodsType
from apps.supply_order.models import AreaWareHouse
from apps.supply_order.models import VaildArea, WomaiOrder
from apps.supply_order.womai_api import WoMaiApi
from apps.supply_order.models import Company
from core.tools.models import Province, City, District
from apps.supply_order.utils import re_goods_detail_wm
from core.tools.oss_upload import upload_network_file


# 577990 622309
class InsertGoods(WoMaiApi):
    @staticmethod
    def create_goods_type():
        """
        导入商品类型数据
        :return:
        """
        goods_type = {
            142: "常温",
            143: "生鲜"
        }
        goods_type_list = []
        for k, v in goods_type.items():
            goods_type_list.append(GoodsType(goods_type=k, name=v))
        GoodsType.objects.bulk_create(goods_type_list)

    # 添加或更新
    def create_or_update_goods(self):
        """
        创建商品
        :return:
        """
        content = self.get_goods_num(1)
        itemlist = content.get("itemlist")
        flag = False
        company = Company.objects.get(sign='womaiwang')
        for i in itemlist:  # id list
            itemid = i.get("itemid")
            content = self.get_goods_detail(itemid)  # 详情返回来的内容
            item_detail = content.get("itemdetail")[0]  # 详情 dict
            if item_detail.get("goodsid") == "577990":
                flag = True
                continue
            if not flag:
                continue
            goodstype = item_detail.pop("goodstype", None)
            if not goodstype:
                continue
            # 商品类型实例
            print(goodstype, item_detail)
            if item_detail.get("pubflag") == '0' or item_detail.get("pubflag") == 0:
                item_detail["pubflag"] = 0
            gt_instance = GoodsType.objects.get(goods_type=goodstype)
            goods_queryset = Goods.objects.filter(goodsid=item_detail.get("goodsid"))
            for k, v in item_detail.items():
                if k == "prodescription":
                    for item in re_goods_detail_wm(v):
                        upload_network_file(item)
                    desc = v.replace("http://pic.womai.com/", "https://m.kalaibao.com/womai/")
                    item_detail[k] = desc
                    print(desc)
                if isinstance(v, str) and v.isdigit():
                    item_detail[k] = int(v)
            item_detail["can_sale"] = False
            item_detail["company"] = company
            if not goods_queryset.exists():
                goods = Goods.objects.create(**item_detail)
                goods.goodstype = gt_instance
                goods.save()
            else:
                goods = goods_queryset[0]
                goods.update_detail(**item_detail)
                goods.goodstype = gt_instance
                goods.save()
            content = self.get_goods_image(itemid)
            itemimage = content.get("itemimage")  # 详情页的图片内容
            for image_list in itemimage:
                path_list = image_list.get("image")  # 图片路径
                for one in path_list:
                    isprimary = one.get("isprimary")  # 排序
                    file_path = one.get("path")  # 路径
                    upload_network_file(file_path)
                    path = file_path.replace("http://pic3.womai.com/", "https://m.kalaibao.com/womai/")
                    self.create_goods_img(goods, isprimary, path)

    # 只追加
    def append_goods(self):
        """
        创建商品
        :return:
        """
        content = self.get_goods_num(2)
        itemlist = content.get("itemlist")
        company = Company.objects.get(sign='womaiwang')
        for i in itemlist:  # id list
            itemid = i.get("itemid")
            content = self.get_goods_detail(itemid)  # 详情返回来的内容
            item_detail = content.get("itemdetail")[0]  # 详情 dict
            goodstype = item_detail.pop("goodstype", None)
            if not goodstype:
                continue
            # 商品类型实例
            print(goodstype, item_detail)
            if item_detail.get("pubflag") == '0' or item_detail.get("pubflag") == 0:
                item_detail["pubflag"] = 0
            gt_instance = GoodsType.objects.get(goods_type=goodstype)
            goods_queryset = Goods.objects.filter(goodsid=item_detail.get("goodsid"))
            if not goods_queryset.exists():
                for k, v in item_detail.items():
                    if k == "prodescription":
                        for item in re_goods_detail_wm(v):
                            upload_network_file(item)
                        desc = v.replace("http://pic.womai.com/", "https://m.kalaibao.com/womai/")
                        item_detail[k] = desc
                        print(desc)
                    if isinstance(v, str) and v.isdigit():
                        item_detail[k] = int(v)
                item_detail["can_sale"] = False
                item_detail["company"] = company
                content = self.get_goods_image(itemid)
                itemimage = content.get("itemimage", [])  # 详情页的图片内容
                if not itemimage:
                    item_detail["pubflag"] = 0
                goods = Goods.objects.create(**item_detail)
                goods.goodstype = gt_instance
                goods.save()
                for image_list in itemimage:
                    path_list = image_list.get("image")  # 图片路径
                    for one in path_list:
                        isprimary = one.get("isprimary")  # 排序
                        file_path = one.get("path")  # 路径
                        upload_network_file(file_path)
                        path = file_path.replace("http://pic3.womai.com/", "https://m.kalaibao.com/womai/")
                        self.create_goods_img(goods, isprimary, path)

    @staticmethod
    def create_goods_img(goods, isprimary, path):
        """
        创建商品图片
        :param goods:
        :param isprimary:
        :param path:
        :return:
        """
        gl_queryset = GoodsImage.objects.filter(goods=goods, isprimary=isprimary, type=4)
        if gl_queryset.exists():
            gl_obj = gl_queryset[0]
            gl_obj.update_path(path)
        else:
            GoodsImage.objects.create(goods=goods, isprimary=isprimary, type=4, path=path)

    # 配送有效范围
    def area_vaild(self):
        """
        配送有效范围
        :return:
        """
        goods_type_queryset = GoodsType.objects.all()
        counties = District.objects.all()
        for county in counties:
            for goods_type in goods_type_queryset:
                type_num = 0 if goods_type.goods_type == 142 else 1
                content = self.get_area_vaild(county.city.province.name, county.city.name, county.name, type_num)
                if content.get("result") is True:
                    VaildArea.objects.get_or_create(
                        district=county,
                        goods_type=goods_type
                    )
                else:
                    VaildArea.objects.filter(
                        district=county,
                        goods_type=goods_type
                    ).delete()

    # 更新库存
    def create_inventory(self):
        queryset = Goods.objects.filter(company__sign="womaiwang")
        count = queryset.count()
        page_num = math.ceil(count / 100.0)
        for i in range(page_num):
            print(i)
            if page_num - i == 1:
                skuids = Goods.objects.filter(company__sign="womaiwang").values_list('goodsid', flat=True)[i*100:]
            else:
                skuids = Goods.objects.filter(company__sign="womaiwang").values_list('goodsid', flat=True)[i*100:(i+1)*100]
            skuids = map(lambda x: str(x), skuids)
            skuids_str = ",".join(skuids)
            area_ware_house = AreaWareHouse.objects.all()
            for area in area_ware_house:
                content = self.get_inventory(
                    skuids_str, area.p_code
                )
                inventory = content.get("Inventory")
                for i in inventory:
                    num = i.get("inventory")
                    skuid = i.get('skuid')
                    goods_obj = Goods.objects.get(goodsid=skuid)
                    in_obj, created = Inventory.objects.get_or_create(
                        goods=goods_obj,
                        ware_house=area
                    )
                    in_obj.num = num
                    in_obj.save()


if __name__ == '__main__':
    insertGoods = InsertGoods()
    insertGoods.append_goods()
    # insertGoods.create_or_update_goods()
    insertGoods.create_inventory()
    # insertGoods.area_vaild()
